#!/bin/bash

# 函数加入 ~/.bashrc
# 从当前目录搜索关键字的所有.h 和 .cpp， 比如 search Scene
function searchw()
{
    grep -IRnw "${1}" `find -L -name \*.h -o -name \*.c 2>/dev/null`
}
function search()
{
    grep -IRn ${1} `find -L -name \*.h -o -name \*.cpp 2>/dev/null`
}

# 如果找Scene定义的位置的话，上述命令会出现很多结果
# search Scene | grep class  | grep -v \;
# 这条语句的含义是：先搜索出所有Scene的语句， 再筛选带有class字样的语句，
# 带有分号的语句排除掉(因为定义class定义后面如果规范写代码是不会有分号的

alias tsh="time sh"
alias tmux="tmux -2"
alias pef="ps -ef"
alias ssapn="ss -apn | grep "
alias gpua="git pull" # 这个会更新本地所有分支
alias gput="gst; gpu; gstp" # 先stash再拉新再stash pop
alias gsu="git status"
alias gbr="git branch"
alias gst="git stash"
alias gstp="git stash pop"
alias gdf="git difftool"
alias gch="git checkout"
alias glog="git log --pretty='%Cred%h%Creset - %s %C(cyan)(%ci) %C(bold blue)<%aN>%Creset %C(yellow)%d%Creset' -10"
alias gadd="git add"
alias gcp="git cherry-pick"
alias gmt="git mergetool"
alias gsnn="git show --stat"
alias gls="git ls-remote"

function add_exist_branch () {
    (( $# < 2 )) && echo "参数：<分支名> <日志深度>" && return 1
    local branch=${1}
    local depth=${2}
    (( $(gls --heads | grep -c -w ${branch}) == 0 )) && echo "分支[${branch}],远端不存在" && return 1

    if (( $(git config --local --get-all remote.origin.fetch | grep -c -w ${branch}) == 0 )); then # 说明没有添加
        git remote set-branches --add origin ${branch}
    fi

    if (( $(gbr -r | grep -w -c origin/${branch}) == 0 )); then # 说明没有拉下来
        git fetch origin ${branch} --depth ${depth}
        (( $? > 0 )) && echo "git fetch 失败，请手动重试" && return 1
    fi

    git checkout ${branch}
    (( $? > 0 )) && echo "git checkout [${branch}] 失败,请手动重试" && return 1
    git push -u origin ${branch}
    echo "Done"

}

function checkout_branch() {
    (( $# < 1 )) && echo "参数: <分支名>" && return 1
    (( $(gls | grep -c -w ${1}) > 0 )) && echo "分支[${1}]已存在,checkout失败" && return 1
    local branch=${1}
    # 先拉最新
    gpu
    (( $? > 0 )) && echo "pull 失败，确定是在git目录?" && return 1
    
    # 切出新分支
    git checkout -b ${branch}
    # 推到远端
    git push origin ${branch}:${branch}
    (( $? > 0 )) && echo "推到远端出错" && return 1
    # 添加监听
    git remote set-branches --add origin ${branch}
    # 设置上游
    git push -u origin ${branch}
    # 更新会追踪
    gpu
    gbr
}

function rops() {
    function help_func() {
        echo "ps <x/e> <grep_key>:   查看进程id，进程名，使用的xml配置"
    }
    if (( $# == 0 )); then
        help_func
        return 1
    fi

    function dump_process() {
        # 传入的参数不合法
        [[ $# < 2 || ! -d /proc/${1} ]] && return 
        # 此进程不是这个server的
        [[ $(pwdx ${1}) != *${2} ]] && return
        # 过滤出想要的
        [[ -n ${3} ]] && [[ $(cat /proc/${1}/cmdline) != *${3}* ]] && return
        ps --pid ${1} -o pid,lstart,cmd | grep -v PID
    }

    # ps命令 查看相关进程
    function ps_func() {
        (( $# < 1 )) && help_func && return 1
        local pwd_key="/${1}"
        shift
        local ps_list=$(ps -eo pid,cmd | grep server | grep xml | awk '{print $1}')
        for pid in ${ps_list}; do
            dump_process ${pid} ${pwd_key} $*
        done
    }
    ps_func $*
}

function gcm() {
    if (( $# < 1 )); then
        echo "至少需要一个参数 <commit msg>"
        return
    fi
    if [[ "--am" == "${1}" ]]; then
        shift 
        if (( $# < 1 )); then
            git commit --am
        else
            git commit --am -m "${*}"
        fi
    else
        git commit -m "${*}"
    fi
}

function scr() {
    if (( $# < 1 )); then
        screen -ls
        return
    fi
    screen -r "${1}"
}

# 删除现有分支
function rembranch() {
    if (( $# < 1 )); then
        echo "参数: 分支名"
        return
    fi
    [[ ! $(git rev-parse --is-inside-work-tree) ]] && echo "当前目录不是git目录" && return
    while (( $# > 0 )); do
        git branch -D ${1}
        if (( $? != 0 )); then
            echo "删除[${1}] 失败,当前分支？"
            shift
            continue
        fi
        git branch -dr origin/${1}
        sed -ie "/\/${1}:/d" $(git rev-parse --show-toplevel)/.git/config
        echo "删除[${1}] 成功"
        shift
    done
    echo ${hint}
}

function gdelremote() {
    (( $# < 1 )) && return
    echo -n "这操作将删除远端的分支,确定要操作吗? [y/n]: "
    read op
    [[ "${op}" != "y" ]] && echo "已取消" && return 
    git push --delete origin $*
}

# rebase某个分支
function greb() {
    local branch_list=($(git branch | grep -v '*' | sed "s:\n: :g"))
    local sz=${#branch_list[@]}
    (( ${sz} < 1 )) && echo "只有当前一个分支,无法rebase" && return 0
    local tgt_branch=
    if (( ${sz} == 1 )); then
        tgt_branch=${branch_list[0]}
    else
        echo "---------------------------------------------------"
        for (( i = 0; i  < ${sz}; i++ )); do
            echo "$(( ${i} + 1 )). ${branch_list[${i}]}"
        done
        echo "---------------------------------------------------"
        read -p "请选择:" user_select && idx=$(( ${user_select} - 1 ))
        if (( ${idx} < 0 )) || (( ${idx} >= ${sz} )); then
            echo "输入错误:${user_select},取消rebase"
            return
        fi
        tgt_branch=${branch_list[${idx}]}
        read -p "选择的是:${tgt_branch}? (Y/n)" confirm

        [[ "${confirm,,}" != "y" ]] && [[ -n ${confirm} ]] && echo "取消rebase" && return
    fi
    git fetch origin ${tgt_branch}:${tgt_branch}
    (( $? != 0 )) && echo "fetch失败" && return
    local current=$(git symbolic-ref --short HEAD)
    local commit=$(git merge-base ${current} ${tgt_branch})
    [[ -z ${commit} ]] && echo "没有祖先,rebase 失败" && return
    git rebase ${tgt_branch}
}

function gpu() {
    local current=$(git symbolic-ref --short HEAD)
    (( $? != 0 )) && echo "当前是git目录吗确认" && return
    git pull -r origin ${current} $*
    (( $? != 0 )) && echo "更新分支[${current}]失败" && return
    echo "更新分支[${current}]成功: $(date +'%Y-%m-%d %T')"
}

# 当前分支与另一个分支和共同祖先
function ganc() {
    (( $# < 1 )) && echo "参数: <另一个分支的名字>" && return
    local current=$(git symbolic-ref --short HEAD)
    (( $? != 0 )) && echo "当前是git目录吗确认" && return
    local other_branch=${1}
    (( $(gbr | grep -c -w ${other_branch}) == 0 )) && echo "分支[${other_branch}]本地不存在" && return
    [[ ${current} == ${other_branch} ]] && echo  "相同分支不用查找比较" && return
    local commit=$(git merge-base ${current} ${other_branch})
    if [[ -z ${commit} ]]; then
        echo "没有祖先"
    else
        echo "祖先: ${commit}"
        local short_commit=${commit:0:7}
        glog -10000 | grep -C 3 ${short_commit}
    fi
}

# 开发环境简单提交
function gdevpush() {
    gadd -u
    gcm 提交
    git push
}

function gprune(){
    rembranch $(git branch | grep -v '*' | sed "s:\n: :g")
}

# 执行make指令,但要检查是否有两个服务器运行
function tmake(){
    if (( $(ps -ef | grep -c masterserver) > 2 )); then                                                                                                                                                                                                                              
        read -p "现在有两个服务器运行着,请确认是否继续:(Y/n)" sel
	if [[ "${sel}" != "y" ]] && [[ "${sel}" != "Y" ]]; then                                                                                                                                                                                                                      
            return
        fi
    fi
    local makej=10
    local target=
    if (( $# > 0 )); then
	if [[ -d ${1} ]]; then
	    target=$(echo "--target ${1}" | sed 's:/::g')
	    if (( $# >  1 )); then
		makej=$(( ${2} ))
            fi
	else
		makej=$(( ${1} ))
	fi
    fi
    echo "target=${target} makej=${makej}"
    time cmake --build . ${target} -j${makej}
}

function wslproxy() {
    #local wslip=192.168.123.18
    local wslip=$(ip route | grep default | awk '{print $3}')
	# 改成你的 http_proxy（局域网）端口号
	export http_proxy="http://${wslip}:7890"
	export https_proxy=$http_proxy
	export HTTP_PROXY=$http_proxy
	export HTTPS_PROXY=$http_proxy
	echo -e "终端代理已开启，windows ip 为 ${wslip}."
	if curl --silent --head --max-time 3 https://www.google.com/ | grep "HTTP.*200" > /dev/null; then
		echo "Google 连通性正常。"
	else
		echo "无法连接到 Google。"
		unset http_proxy HTTP_PROXY https_proxy HTTPS_PROXY
		echo -e "终端代理已关闭。"
	fi
}


function wslunproxy(){
    unset http_proxy HTTP_PROXY https_proxy HTTPS_PROXY
    echo -e "终端代理已关闭。"
}

if [[ "$OSTYPE" != "msys" ]]; then
    #if [[ -z $TMUX ]]; then
        # tmux里面的操作不要杀
        #pkill ssh-agent
    #fi

    #if [[ -z "$SSH_AUTH_SOCK" ]]; then
        #eval `ssh-agent`
    #fi

    function ref_agent_env() {
        local agents=($(find /tmp/ssh* -name agent*))
        if (( ${#agents[@]} < 1 )); then
            echo "没有可用的ssh-agent,refresh失败"
            return
        fi
        if (( ${#agents[@]} == 1 )); then
            export SSH_AUTH_SOCK=${agents[0]}
            echo "刷新成功: ${SSH_AUTH_SOCK}"
            return
        else
            for agent in ${agents[@]}; do
                local pid=$(($(echo ${agent} | awk -F"." '{print $NF}') + 1))
                if (( $(ps -ef | grep -c -w ${pid}) > 1 )); then
                    export SSH_AUTH_SOCK=${agent}
                    echo "刷新成功: ${SSH_AUTH_SOCK}"
                    return
                fi
            done
        fi
        echo "刷新失败"
    }

    #if [[ ${TERM} != "screen" ]]; then
        # screen不需要
        #ref_agent_env
    #fi
fi
